using System.Collections.Generic;
using UnityEngine;
using UnityEngine.U2D;

public class WaterSpring : MonoBehaviour
{
    public float velocity;

    public float force;

    // current height
    public float height;
    public Transform springTransform;

    [SerializeField] private SpriteShapeController spriteShapeController;

    private readonly float resistance = 40f;

    private List<WaterSpring> springs = new();

    // normal height
    private float target_height;
    private int waveIndex;

    private void OnCollisionEnter2D(Collision2D other)
    {
        if (other.gameObject.CompareTag("pitfall"))
        {
            var rb = other.gameObject.GetComponent<Rigidbody2D>();
            var speed = rb.velocity;

            velocity += speed.y / resistance;
        }
    }

    public void Init(SpriteShapeController ssc)
    {
        var index = transform.GetSiblingIndex();
        waveIndex = index + 1;

        spriteShapeController = ssc;
        velocity = 0;
        height = transform.localPosition.y;
        target_height = transform.localPosition.y;
    }

    // with dampening
    // adding the dampening to the force
    public void WaveSpringUpdate(float springStiffness, float dampening)
    {
        height = transform.localPosition.y;
        // maximum extension
        var x = height - target_height;
        var loss = -dampening * velocity;

        force = -springStiffness * x + loss;
        velocity += force;
        var y = transform.localPosition.y;
        transform.localPosition = new Vector3(transform.localPosition.x, y + velocity, transform.localPosition.z);
    }

    public void WavePointUpdate()
    {
        if (spriteShapeController != null)
        {
            var waterSpline = spriteShapeController.spline;
            var wavePosition = waterSpline.GetPosition(waveIndex);
            waterSpline.SetPosition(waveIndex, new Vector3(wavePosition.x, transform.localPosition.y, wavePosition.z));
        }
    }
}